package cn.edu.scau.dormitory_management_system.controller;


import cn.edu.scau.dormitory_management_system.entity.RoleEntity;
import cn.edu.scau.dormitory_management_system.entity.UserEntity;
import cn.edu.scau.dormitory_management_system.entity.UserRoleEntity;
import cn.edu.scau.dormitory_management_system.entity.dto.RoleDto;
import cn.edu.scau.dormitory_management_system.module.user.service.UserService;
import cn.edu.scau.dormitory_management_system.service.RoleService;
import cn.edu.scau.dormitory_management_system.service.UserRoleService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * 
 *
 * @author wanglingfu
 * @email 1006340605@qq.com
 * @date 2021-08-02 14:35:10
 */
@RestController
@RequestMapping("/admin/admin")
public class AdminController {
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserService userService;
    @PostMapping("/save")
    public Object add(@RequestParam("username")String username,
                      @RequestParam("password")String password  ,
                      @RequestParam("email")String email,
                      @RequestParam("mobile")String mobile,
                      @RequestParam("status")int status,
                      @RequestParam("roleIdList") String roleIdList,
                      HttpServletRequest request){
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(username);
        userEntity.setPassword(password);
        userEntity.setEmail(email);
        userEntity.setMobile(mobile);
        userEntity.setIsEnabled(status);
        int register = userRoleService.register(userEntity);
        JSONObject object = new JSONObject();
        if(register != -1 && register != -2){
            String[] roleList = roleIdList.split(",");
            UserEntity admin = (UserEntity) request.getAttribute("admin");
            int authorization = userRoleService.authorization(roleList, register, admin.getUserId());
            if(authorization > 0){
                object.put("code",200);
                object.put("msg","添加成功");
                return object;
            }
        }else if(register == -2){
            object.put("code",0);
            object.put("msg","用户名重复");
            return object;
        }
        object.put("code",0);
        object.put("msg","注册失败");
        return object;
    }
    @PostMapping("/update")
    public Object update(@RequestParam("username")String username,
                         @RequestParam("userId")int userId,
                      @RequestParam("password")String password  ,
                      @RequestParam("email")String email,
                      @RequestParam("mobile")String mobile,
                      @RequestParam("status")int status,
                      @RequestParam("roleIdList") String roleIdList,
                      HttpServletRequest request){
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(userId);
        userEntity.setUserName(username);
        userEntity.setPassword(password);
        userEntity.setEmail(email);
        userEntity.setMobile(mobile);
        userEntity.setIsEnabled(status);
        boolean update = false;
        int register = 0;
        if (password.equals("")){
            UpdateWrapper<UserEntity> wrapper = new UpdateWrapper<>();
            wrapper.eq("user_id", userId);
            wrapper.set("user_name",username);
            wrapper.set("email",email);
            wrapper.set("mobile",mobile);
            wrapper.set("is_enabled",status);
            update = userService.update(wrapper);
        }else{
            register = userRoleService.update(userEntity);
        }
        JSONObject object = new JSONObject();
        if(register != -1 || update){
            String[] roleList = roleIdList.split(",");
            UserEntity admin = (UserEntity) request.getAttribute("admin");
            int authorization = userRoleService.authorization(roleList, register, admin.getUserId());
            if(authorization > 0 || update){
                object.put("code",200);
                object.put("msg","添加成功");
                return object;
            }
        }
        object.put("code",0);
        object.put("msg","注册失败");
        return object;
    }

    /**
     *
     * @return
     */
    @GetMapping("/info/{userId}")
    public Object info(@PathVariable int userId){
        RoleDto info = userRoleService.info(userId);
        JSONObject object = new JSONObject();
        object.put("user", info);
        object.put("code", 200);
        object.put("msg", "查询成功");
        return object;
    }
    @GetMapping("/list")
    public Object list(@RequestParam("page")int page,
                       @RequestParam("limit")int limit,
                       @RequestParam("username")String username){
        Page<UserEntity> userEntityPage = new Page<>(page,limit);
        QueryWrapper<UserEntity> userEntityQueryWrapper = new QueryWrapper<>();
        userEntityQueryWrapper.eq("is_admin",1)
                            .like("user_name",username)
                            .ne("user_id",0);
        Page<UserEntity> page1 = userService.page(userEntityPage, userEntityQueryWrapper);
        JSONObject object = new JSONObject();
        object.put("page", page1);
        object.put("code", 200);
        object.put("msg", "查询成功");
        return object;
    }
    @PostMapping("/delete")
    public Object delete(@RequestParam("userIds")String userIds){
        String[] split = userIds.split(",");
        for (int i = 0; i < split.length; i++) {
            userService.removeById(Integer.valueOf(split[i]));
            HashMap<String, Object> map = new HashMap<>();
            map.put("user_id",Integer.valueOf(split[i]));
            userRoleService.removeByMap(map);
        }
        JSONObject object = new JSONObject();
        object.put("code", 200);
        object.put("msg", "删除成功");
        return object;
    }
}
